﻿using MediatR;
using Medical.Api.Write.Application.Command.DepartmentManagement.Sign;
using Medical.Domain.Wms;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Medical.Api.Write.Application.Handler.DepartmentManagement.Sign
{
    /// <summary>
    /// 更新发放表状态处理程序
    /// </summary>
    public class UpdateSignStatusCommandHandler : IRequestHandler<UpdateSignStatusCommands, ApiResult<int>>
    {
        private readonly IBaseRepository<WmsLssue> lssueRep; 
        private readonly ILogger<UpdateSignStatusCommandHandler> logger;

        /// <summary>
        /// 构造函数，注入所需依赖
        /// </summary>
        /// <param name="lssueRep">发放表仓储</param>
        /// <param name="logger">日志记录器</param>
        public UpdateSignStatusCommandHandler(IBaseRepository<WmsLssue> lssueRep, ILogger<UpdateSignStatusCommandHandler> logger)
        {
            this.lssueRep = lssueRep;
            this.logger = logger;
        }

        /// <summary>
        /// 处理更新发放表状态命令
        /// </summary>
        /// <param name="request">更新发放表状态命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>API结果</returns>
        public async Task<ApiResult<int>> Handle(UpdateSignStatusCommands request, CancellationToken cancellationToken)
        {
            try
            {
                logger.LogInformation("开始处理发放表状态更新，ID：{0}，新状态：{1}", request.LssueId, request.LssueState);
                
                // 检查要修改的发放记录是否存在
                var existingLssue = await lssueRep.GetModelAsync(request.LssueId);
                if (existingLssue == null)
                {
                    logger.LogWarning("未找到ID为{0}的发放记录", request.LssueId);
                    return new ApiResult<int>
                    {
                        Code = ApiEnums.NotFound,
                        Data = 0,
                        Msg = $"未找到ID为{request.LssueId}的发放记录"
                    };
                }
                
                // 更新发放状态
                existingLssue.LssueState = request.LssueState;
                existingLssue.UpdateTime = DateTime.Now;
                
                // 更新发放记录 - Update方法内部已经调用了SaveChanges
                lssueRep.Update(existingLssue);
                
                logger.LogInformation("成功更新发放表状态，ID：{0}，新状态：{1}", request.LssueId, request.LssueState);
                return new ApiResult<int>
                {
                    Code = ApiEnums.Success,
                    Data = request.LssueId,
                    Msg = "成功更新发放表状态"
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "更新发放表状态时发生错误：{0}", ex.Message);
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Data = 0,
                    Msg = $"更新发放表状态失败：{ex.Message}"
                };
            }
        }
    }
}
